"""



"""
import logging
from flask import current_app,render_template, jsonify
from flask import request
from flask import session

from info.models import User, News, Category
from info.utils.response_code import RET
from . import index_bule

# 首页新闻列表
# 请求路径: /newslist
# 请求方式: GET
# 请求参数: cid,page,per_page
# 返回值: data数据
@index_bule.route('/newslist')
def newslist():
    #1, 获取参数
    cid = request.args.get("cid","1")#获取要查询第几页的页码
    page = request.args.get("page","1")
    per_page = request.args.get("per_page","5")

    #2, 参数类型转换(整数),方便做分页查询
    try:
        page =  int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1
        per_page = 5

    #3, 分页查询数据,组织数据
    try:

        #3,1 判断是否是cid==1, 如果是1表示获取最新新闻, 按照时间倒序排列就是最新新闻
        condition = ""

        if cid != "1":
            condition = (News.category_id == cid)

        paginate = News.query.filter(condition).order_by(News.create_time.desc()).paginate(page, per_page,
                                                                                                       False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")

    totalPage = paginate.pages # 共有多少页
    items = paginate.items #当前页数的所有对象
    currentPage = paginate.page #当前页

    #3,1 将对象列表转成字典列表
    newList = []
    for news in items:
        newList.append(news.to_dict())

    #4,返回响应,携带数
    return jsonify(errno=RET.OK,errmsg="获取成功",totalPage=totalPage,currentPage=currentPage,newsList=newList)


@index_bule.route("/",methods=['GET','POST'])
def show_index():

    #1获取用户编号
    # user_id = session.get['user_id']
    user_id = session.get("user_id")
    #2获取该用户对象
    user = None
    if user_id:
        user = User.query.get(user_id)

    #3,按照点击量,查询前10条新闻
    try:
        news_list = News.query.order_by(News.clicks).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)

    #4,将新闻对象列表, 转成新闻的字典列表
    click_news_list = []
    for news in news_list:
        click_news_list.append(news.to_dict())


    #5,查询所有的分类,转成字典列表
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    category_list = []

    for category in categories:
        category_list.append(category.to_dict())

    #生成渲染数据
    dict_data = {
        "user_info":user.to_dict() if user else "",
        "click_news_list":click_news_list,
        "categories":category_list
    }

    return render_template("news/index.html",data = dict_data)


# 处理网站，，，logo展示出现问题？？？？？？？？？？？？？？？？？？？？？？？？？？？
# @index_bule.route("/favicon.ico")
# def get_logo():
#     response = current_app.send_static_file("news/favicon.ico")
#     return response
#
